package com.nutiteq.directions;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

public class LinePropertiesForm extends Form implements CommandListener {

  private final DirectionsCanvas canvas;

  private TextField width;
  private TextField colorR;
  private TextField colorG;
  private TextField colorB;

  private final Command back = new Command("Back", Command.BACK, 0);
  private final Command setStyle = new Command("Set style", Command.OK, 0);

  private final int lineWidth;

  private int redPart;
  private int greenPart;
  private int bluePart;

  public LinePropertiesForm(final DirectionsCanvas canvas, final int lineWidth, final int lineColor) {
    super("Line properties");
    this.canvas = canvas;
    this.lineWidth = lineWidth;

    width = new TextField("Line width (in pixels)", Integer.toString(lineWidth), 2, TextField.ANY);
    redPart = getRedPart(lineColor);
    colorR = new TextField("Line color red part (0-255)", Integer.toString(redPart), 3,
        TextField.ANY);
    greenPart = getGreenPart(lineColor);
    colorG = new TextField("Line color green part (0-255)", Integer.toString(greenPart), 3,
        TextField.ANY);
    bluePart = getBluePart(lineColor);
    colorB = new TextField("Line color blue part (0-255)", Integer.toString(bluePart), 3,
        TextField.ANY);

    append(width);
    append(colorR);
    append(colorG);
    append(colorB);
    addCommand(back);
    addCommand(setStyle);
    setCommandListener(this);
  }

  private int getRedPart(final int lineColor) {
    return colorPart(lineColor, 16);
  }

  private int getGreenPart(int lineColor) {
    return colorPart(lineColor, 8);
  }

  private int getBluePart(int lineColor) {
    return colorPart(lineColor, 0);
  }

  public int colorPart(final int color, final int shift) {
    return (color >> shift) & 0xFF;
  }

  public void commandAction(final Command cmd, final Displayable d) {
    if (cmd == setStyle) {
      final int w = checkNumber(width.getString(), lineWidth);
      final int color = mergeColors(checkNumber(colorR.getString(), redPart), checkNumber(colorG
          .getString(), greenPart), checkNumber(colorB.getString(), bluePart));
      canvas.setLineStyle(w, color);
    }

    Display.getDisplay(Directions.instance).setCurrent(canvas);
  }

  private int mergeColors(int r, int g, int b) {
    return 0xFF << 24 | r << 16 | g << 8 | b;
  }

  private int checkNumber(final String number, final int defaultValue) {
    try {
      return Integer.parseInt(number);
    } catch (NumberFormatException e) {
      return defaultValue;
    }
  }
}
